import {Express} from "express";
import {NodeModulesScanner} from "../scanner/NodeModulesScanner";
import {globalConfig} from "../config";
import fs from 'fs-extra';
import path from 'path';
import {FileUtil} from "../utils/FileUtil";

export function CleanupService(app: Express) {
  const prefix = '/api/cleanup';

  // 获取node_modules列表
  app.get(prefix + '/node_modules', async (req, res) => {
    try {
      const targetDir = globalConfig.config.scan.targetDir;
      const nodeModulesDir = await NodeModulesScanner.scan(targetDir);
      res.json(nodeModulesDir);
    } catch (error) {
      console.error('获取node_modules列表失败:', error);
      res.status(500).json({error: `服务器错误: ${(error as Error).message}`});
    }
  });

  // 清理指定路径，清理前判断是否为能够清理的内容，如果能够清理则直接清理，否则返回原因。如果传参为能够直接删除则不校验
  app.delete(prefix + '/path', async (req, res) => {
    try {
      const {paths, force = false} = req.body;

      if (!paths || !Array.isArray(paths) || paths.length === 0) {
        return res.status(400).json({error: '缺少目标路径或路径格式不正确，应为数组格式'});
      }

      const results = [];
      const errors = [];

      // 逐个处理每个路径
      for (const targetPath of paths) {
        try {
          // 验证路径是否存在
          if (!await fs.pathExists(targetPath)) {
            errors.push({path: targetPath, error: '指定路径不存在'});
            continue;
          }

          // 如果不是强制模式，进行安全性检查
          if (!force) {
            // 检查是否是node_modules目录
            const isNodeModules = path.basename(targetPath) === 'node_modules' ||
              targetPath.includes(path.sep + 'node_modules' + path.sep);

            // 验证是否是安全的删除目标
            if (!isNodeModules) {
              errors.push({
                path: targetPath,
                error: '目标不是可安全清理的内容',
                details: '只允许清理node_modules目录，或使用force=true参数强制删除'
              });
              continue;
            }
          }

          // 执行删除操作
          await FileUtil.deleteDirectory(targetPath);
          results.push({path: targetPath, success: true});
        } catch (error) {
          errors.push({path: targetPath, error: (error as Error).message});
        }
      }

      res.json({
        success: errors.length === 0,
        results,
        errors
      });
    } catch (error) {
      console.error('清理路径失败:', error);
      res.status(500).json({error: `服务器错误: ${(error as Error).message}`});
    }
  });
}
